<template>
  <div class="dashboard-container">
    <!-- 顶部滚动新闻 -->
    <el-card class="news-ticker-card" :body-style="{ padding: '8px 15px' }">
      <div class="news-ticker">
        <div class="news-ticker-icon">
          <el-icon><Warning /></el-icon>
        </div>
        <div class="news-ticker-content">
          <div class="news-ticker-wrapper">
            <div 
              class="news-ticker-item" 
              :style="{ transform: `translateX(${-currentScrollPosition}px)` }"
              ref="tickerItem"
            >
              <template v-for="(task, index) in exceptionTasks" :key="index">
                <span class="news-ticker-badge">{{ task.type }}</span>
                {{ task.title }}
                <span class="news-ticker-time">截止时间: {{ task.deadline }}</span>
                <span class="news-ticker-separator">|</span>
              </template>
            </div>
          </div>
        </div>
        <div class="news-ticker-actions">
          <el-button type="danger" size="small" plain @click="viewAllExceptions">
            查看全部
          </el-button>
        </div>
      </div>
    </el-card>

    <el-row :gutter="20" class="statistics-row">
      <!-- 统计卡片 -->
      <el-col :xs="24" :sm="12" :md="6" v-for="(item, index) in statisticsData" :key="index">
        <el-card class="statistics-card" :body-style="{ padding: '15px' }">
          <div class="statistics-content">
            <div class="statistics-icon">
              <img :src="item.image" alt="" class="statistics-image" />
            </div>
            <div class="statistics-info">
              <div class="statistics-title">{{ item.title }}</div>
              <div class="statistics-value">{{ item.value }}</div>
              <div class="statistics-change" :class="item.isIncrease ? 'increase' : 'decrease'">
                <el-icon>
                  <component :is="item.isIncrease ? 'ArrowUp' : 'ArrowDown'"></component>
                </el-icon>
                {{ item.changeRate }}%
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="chart-row">
      <!-- 运单趋势图 -->
      <el-col :xs="24" :lg="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>运单趋势</span>
              <el-radio-group v-model="orderTrendTimeRange" size="small">
                <el-radio-button label="week">本周</el-radio-button>
                <el-radio-button label="month">本月</el-radio-button>
                <el-radio-button label="year">全年</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div class="chart-container" ref="orderTrendChart"></div>
        </el-card>
      </el-col>

      <!-- 运输成本分析 -->
      <el-col :xs="24" :lg="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>运输成本分析</span>
              <el-select v-model="costAnalysisType" size="small" style="width: 120px">
                <el-option label="按车型" value="vehicle"></el-option>
                <el-option label="按区域" value="region"></el-option>
                <el-option label="按承运商" value="carrier"></el-option>
              </el-select>
            </div>
          </template>
          <div class="chart-container" ref="costAnalysisChart"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="chart-row">
      <!-- 运输地图 -->
      <el-col :span="24">
        <el-card class="map-card">
          <template #header>
            <div class="card-header">
              <span>实时运输地图</span>
              <el-switch
                v-model="showAllVehicles"
                active-text="显示所有车辆"
                inactive-text="仅显示异常"
              ></el-switch>
            </div>
          </template>
          <div class="map-container" ref="transportMap"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="table-row">
      <!-- 待处理任务 -->
      <el-col :span="24">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>待处理任务</span>
              <el-button type="primary" size="small" plain>查看全部</el-button>
            </div>
          </template>
          <el-table :data="pendingTasks" style="width: 100%" :max-height="300">
            <el-table-column prop="id" label="任务ID" width="100"></el-table-column>
            <el-table-column prop="type" label="类型" width="120">
              <template #default="scope">
                <el-tag :type="getTaskTypeTag(scope.row.type)">{{ scope.row.type }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="title" label="标题"></el-table-column>
            <el-table-column prop="priority" label="优先级" width="100">
              <template #default="scope">
                <el-tag :type="getPriorityTag(scope.row.priority)" size="small">
                  {{ scope.row.priority }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="deadline" label="截止时间" width="180"></el-table-column>
            <el-table-column label="操作" width="150">
              <template #default="scope">
                <el-button type="primary" size="small" @click="handleTask(scope.row)">处理</el-button>
                <el-button type="info" size="small" plain @click="viewTaskDetail(scope.row)">详情</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue'
import * as echarts from 'echarts'
import { ArrowUp, ArrowDown, Warning } from '@element-plus/icons-vue'
import AMapLoader from '@amap/amap-jsapi-loader'

// 导入图片
import todayImage from '@/assets/today.png'
import truckImage from '@/assets/truck.png'
import errorImage from '@/assets/error.png'
import incomeImage from '@/assets/income.png'

// 统计数据
const statisticsData = ref([
  {
    title: '今日运单',
    value: '1,286',
    changeRate: '15.8',
    isIncrease: true,
    image: todayImage,
    color: '#409EFF'
  },
  {
    title: '在途车辆',
    value: '358',
    changeRate: '8.2',
    isIncrease: true,
    image: truckImage,
    color: '#67C23A'
  },
  {
    title: '异常订单',
    value: '12',
    changeRate: '3.5',
    isIncrease: false,
    image: errorImage,
    color: '#E6A23C'
  },
  {
    title: '今日收入',
    value: '¥286,432',
    changeRate: '12.3',
    isIncrease: true,
    image: incomeImage,
    color: '#F56C6C'
  }
])

// 图表引用
const orderTrendChart = ref(null)
const costAnalysisChart = ref(null)
const transportMap = ref(null)

// 图表实例
let orderTrendChartInstance = null
let costAnalysisChartInstance = null
let mapInstance = null

// 图表配置
const orderTrendTimeRange = ref('week')
const costAnalysisType = ref('vehicle')
const showAllVehicles = ref(true)

// 待处理任务
const pendingTasks = ref([
  {
    id: 'T-2025031401',
    type: '订单审核',
    title: '紧急订单审核 - 上海至北京',
    priority: '高',
    deadline: '2025-03-14 16:30:00'
  },
  {
    id: 'T-2025031402',
    type: '异常处理',
    title: '车辆延误 - 广州至深圳',
    priority: '高',
    deadline: '2025-03-14 15:00:00'
  },
  {
    id: 'T-2025031403',
    type: '文档确认',
    title: '回单确认 - 武汉至长沙',
    priority: '中',
    deadline: '2025-03-15 10:00:00'
  },
  {
    id: 'T-2025031404',
    type: '费用审核',
    title: '额外费用审核 - 成都至重庆',
    priority: '中',
    deadline: '2025-03-15 14:00:00'
  },
  {
    id: 'T-2025031405',
    type: '计划调整',
    title: '运输计划调整 - 南京至杭州',
    priority: '低',
    deadline: '2025-03-16 09:00:00'
  }
])

// 筛选异常处理任务
const exceptionTasks = computed(() => {
  return pendingTasks.value.filter(task => task.type === '异常处理' || task.priority === '高')
})

// 滚动新闻相关
const currentScrollPosition = ref(0)
const tickerItem = ref(null)
const scrollSpeed = 1 // 滚动速度，可以调整
const animationFrame = ref(null)
const tickerWidth = ref(0)
const containerWidth = ref(0)

// 启动滚动新闻
const startNewsTicker = () => {
  if (exceptionTasks.value.length === 0) return
  
  // 等待DOM更新完成后获取元素宽度
  setTimeout(() => {
    if (tickerItem.value) {
      tickerWidth.value = tickerItem.value.scrollWidth
      containerWidth.value = tickerItem.value.parentElement.clientWidth
      
      // 开始动画
      animateScroll()
    }
  }, 500)
}

// 停止滚动新闻
const stopNewsTicker = () => {
  if (animationFrame.value) {
    cancelAnimationFrame(animationFrame.value)
    animationFrame.value = null
  }
}

// 滚动动画
const animateScroll = () => {
  currentScrollPosition.value += scrollSpeed
  
  // 当滚动到末尾时重置位置
  if (currentScrollPosition.value >= tickerWidth.value) {
    currentScrollPosition.value = -containerWidth.value
  }
  
  animationFrame.value = requestAnimationFrame(animateScroll)
}

// 查看所有异常
const viewAllExceptions = () => {
  // 跳转到待处理任务页面或打开任务列表
  ElMessage.info('跳转到异常处理页面')
}

// 任务类型标签
const getTaskTypeTag = (type) => {
  const typeMap = {
    '订单审核': 'primary',
    '异常处理': 'danger',
    '文档确认': 'success',
    '费用审核': 'warning',
    '计划调整': 'info'
  }
  return typeMap[type] || 'info'
}

// 优先级标签
const getPriorityTag = (priority) => {
  const priorityMap = {
    '高': 'danger',
    '中': 'warning',
    '低': 'info'
  }
  return priorityMap[priority] || 'info'
}

// 处理任务
const handleTask = (task) => {
  console.log('处理任务:', task)
  // 实际应用中应该跳转到对应的处理页面
}

// 查看任务详情
const viewTaskDetail = (task) => {
  console.log('查看任务详情:', task)
  // 实际应用中应该显示详情弹窗或跳转到详情页
}

// 初始化运单趋势图
const initOrderTrendChart = () => {
  if (orderTrendChartInstance) {
    orderTrendChartInstance.dispose()
  }
  
  orderTrendChartInstance = echarts.init(orderTrendChart.value)
  
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['总运单', '已完成', '在途中', '异常']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '总运单',
        type: 'line',
        stack: '总量',
        data: [120, 132, 101, 134, 90, 230, 210],
        smooth: true,
        lineStyle: {
          width: 3
        }
      },
      {
        name: '已完成',
        type: 'line',
        stack: '总量',
        data: [110, 122, 91, 124, 80, 190, 180],
        smooth: true
      },
      {
        name: '在途中',
        type: 'line',
        stack: '总量',
        data: [8, 9, 8, 8, 9, 38, 28],
        smooth: true
      },
      {
        name: '异常',
        type: 'line',
        stack: '总量',
        data: [2, 1, 2, 2, 1, 2, 2],
        smooth: true
      }
    ]
  }
  
  orderTrendChartInstance.setOption(option)
}

// 初始化成本分析图
const initCostAnalysisChart = () => {
  if (costAnalysisChartInstance) {
    costAnalysisChartInstance.dispose()
  }
  
  costAnalysisChartInstance = echarts.init(costAnalysisChart.value)
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center',
      data: ['重型卡车', '中型卡车', '轻型卡车', '厢式货车', '冷藏车']
    },
    series: [
      {
        name: '运输成本',
        type: 'pie',
        radius: ['50%', '70%'],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { value: 335, name: '重型卡车' },
          { value: 310, name: '中型卡车' },
          { value: 234, name: '轻型卡车' },
          { value: 135, name: '厢式货车' },
          { value: 148, name: '冷藏车' }
        ]
      }
    ]
  }
  
  costAnalysisChartInstance.setOption(option)
}

// 初始化地图
const initMap = async () => {
  try {
    const AMap = await AMapLoader.load({
      key: '您的高德地图API密钥', // 实际应用中需要替换为有效的API密钥
      version: '2.0',
      plugins: ['AMap.ToolBar', 'AMap.Scale', 'AMap.HawkEye', 'AMap.MapType', 'AMap.Geolocation']
    })
    
    mapInstance = new AMap.Map(transportMap.value, {
      zoom: 5,
      center: [116.397428, 39.90923] // 北京
    })
    
    // 添加控件
    mapInstance.addControl(new AMap.ToolBar())
    mapInstance.addControl(new AMap.Scale())
    
    // 模拟添加车辆标记
    const mockVehicles = [
      { position: [116.397428, 39.90923], status: 'normal', info: '京A12345 - 正常' },
      { position: [121.473701, 31.230416], status: 'normal', info: '沪B67890 - 正常' },
      { position: [113.264385, 23.129112], status: 'warning', info: '粤C12345 - 延误' },
      { position: [114.298572, 30.584355], status: 'normal', info: '鄂D56789 - 正常' },
      { position: [104.066541, 30.572269], status: 'danger', info: '川E12345 - 故障' }
    ]
    
    mockVehicles.forEach(vehicle => {
      const marker = new AMap.Marker({
        position: vehicle.position,
        icon: new AMap.Icon({
          // 根据状态使用不同图标
          image: `../assets/vehicle-${vehicle.status}.png`,
          size: new AMap.Size(32, 32),
          imageSize: new AMap.Size(32, 32)
        }),
        title: vehicle.info
      })
      
      mapInstance.add(marker)
    })
    
  } catch (e) {
    console.error('地图加载失败:', e)
  }
}

// 监听窗口大小变化，重绘图表
const handleResize = () => {
  if (orderTrendChartInstance) {
    orderTrendChartInstance.resize()
  }
  if (costAnalysisChartInstance) {
    costAnalysisChartInstance.resize()
  }
}

onMounted(() => {
  // 初始化图表
  initOrderTrendChart()
  initCostAnalysisChart()
  initMap()
  
  // 启动滚动新闻
  startNewsTicker()
  
  // 添加窗口大小变化监听
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  // 移除窗口大小变化监听
  window.removeEventListener('resize', handleResize)
  
  // 销毁图表实例
  if (orderTrendChartInstance) {
    orderTrendChartInstance.dispose()
  }
  if (costAnalysisChartInstance) {
    costAnalysisChartInstance.dispose()
  }
  if (mapInstance) {
    mapInstance.destroy()
  }
  
  // 停止滚动新闻
  stopNewsTicker()
})
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
}

/* 滚动新闻样式 */
.news-ticker-card {
  margin-bottom: 15px;
}

.news-ticker {
  display: flex;
  align-items: center;
  height: 36px;
}

.news-ticker-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 30px;
  color: #F56C6C;
  font-size: 18px;
}

.news-ticker-content {
  flex: 1;
  overflow: hidden;
  position: relative;
}

.news-ticker-wrapper {
  width: 100%;
  overflow: hidden;
  white-space: nowrap;
}

.news-ticker-item {
  display: inline-block;
  white-space: nowrap;
  will-change: transform;
}

.news-ticker-badge {
  background-color: #F56C6C;
  color: white;
  padding: 1px 6px;
  border-radius: 3px;
  margin-right: 8px;
  font-size: 12px;
}

.news-ticker-time {
  color: #909399;
  margin-left: 8px;
  font-size: 12px;
}

.news-ticker-separator {
  margin: 0 15px;
  color: #DCDFE6;
}

.news-ticker-actions {
  margin-left: 15px;
}

/* 统计卡片样式 */
.statistics-row {
  margin-bottom: 20px;
}

.statistics-card {
  margin-bottom: 20px;
  transition: all 0.3s;
}

.statistics-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.statistics-content {
  display: flex;
  align-items: center;
}

.statistics-icon {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
}

.statistics-image {
  width: 36px;
  height: 36px;
  object-fit: contain;
}

.statistics-info {
  flex: 1;
}

.statistics-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 5px;
}

.statistics-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 5px;
}

.statistics-change {
  font-size: 12px;
  display: flex;
  align-items: center;
}

.increase {
  color: #67C23A;
}

.decrease {
  color: #F56C6C;
}

.chart-row {
  margin-bottom: 20px;
}

.chart-card {
  margin-bottom: 20px;
}

.chart-container {
  height: 350px;
}

.map-card {
  margin-bottom: 20px;
}

.map-container {
  height: 500px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-row {
  margin-bottom: 20px;
}
</style>
